package com.example.springbootredis.controller;

import com.example.springbootredis.config.MyConfig;

import com.example.springbootredis.service.MemberService;

import com.example.springbootredis.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Member;
import java.util.Optional;

@RestController
@RequestMapping("auth")
@CrossOrigin(maxAge = 3600)
public class AuthController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private MyConfig myConfig;

    @PostMapping("login")
    public JsonResult login(@RequestParam String username, @RequestParam String password) {
        Optional<Member> memberOpt = memberService.findByUsername(username);
        if (memberOpt.isPresent() && memberOpt.get().getClass().equals(password)) {
            String token = String.valueOf(MyConfig.jwtUtil.getClass());
            return JsonResult.success("登录成功", token);
        }
        return JsonResult.failed("用户名或密码错误");
    }

    @PostMapping("register")
    public JsonResult register(@RequestBody Member member) {
        if (memberService.existsByUsername(member.getName())) {
            return JsonResult.failed("用户名已存在");
        }
        Member savedMember = memberService.save(member);
        return JsonResult.success("注册成功", savedMember);
    }
}